package com.ltsznh.android.anti_villain;

import android.content.Context;
import android.media.MediaRecorder;
import android.os.Vibrator;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by 涛 on 2014/7/24.
 */
public final class PhoneListener extends PhoneStateListener {
    public Context context;
    private ARecorder recorder;
    private String num;

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        super.onCallStateChanged(state, incomingNumber);
        Log.v("dddd", "onCallStateChanged******************");

//        if(AntiVillainReceiver.IO.equals("O")){
//            return;
//        }
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);

        try {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING://来电
                    num = incomingNumber;
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK://接通电话
                    vibrator.vibrate(200);//震动一下
                    if(AntiVillainReceiver.IO.equals("O")){
                        num = AntiVillainReceiver.num;
                    }
                    if(recorder != null){
                        if(recorder.isRecording){
                            Toast.makeText(context, "电话已挂断，录音停止", Toast.LENGTH_SHORT).show();
                        }
                        recorder.release();
                        recorder = null;
                    }
                    recorder = new ARecorder(context,"call",num,AntiVillainReceiver.IO, MediaRecorder.AudioSource.VOICE_CALL);
                    Toast.makeText(context, "录音开始", Toast.LENGTH_SHORT).show();
                    AntiVillainReceiver.IO = "I";
                    break;
                case TelephonyManager.CALL_STATE_IDLE://挂断电话
                    if (recorder != null) {
                        if(recorder.isRecording){
                            Toast.makeText(context, "电话已挂断，录音停止", Toast.LENGTH_SHORT).show();
                            //震动一下
                            vibrator.vibrate(200);
                        }
                        recorder.release();
                        recorder = null;
                    }
                    AntiVillainReceiver.IO = "I";
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.v("dddd", "call state:" + state);
    }
}
